﻿


using IotClientService.Handles;
using IotClientService.Operations.plc;
using IotContract.Dtos.Clients.Equips;
using IotContract.Dtos.Servers;
using IotContract.Enums;
using IotContract.Events;
using IotContract.Interfaces;
using IotContract.Models.Clients;
using IotContract.Models.Clients.Hks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Extensions;

namespace IotClientService.Operations.hk;
/// <summary>
/// 杭可ocv和充放电操作信息
/// </summary>
public class HkOcvFmtOperation : IEquipOperation<HkOcvFmtEquipDto>
{
   

   
   
    private CancellationTokenSource _cancellationTokenSource;

    private Task _operationTask;




    private HkOcvFmtEquipDto _group;

    private OcvFmtTcpHandle _tcpHandle;

    private IConnectDataService _connectDataService;










    private bool _status = false;
    public event EventHandler<ConnectStatusEventArgs> OnConnectStatusChanged;

    public HkOcvFmtOperation(IConnectDataService connectDataService)
    {
        _connectDataService=connectDataService;
        _tcpHandle = new OcvFmtTcpHandle();
        _tcpHandle.OnConnectLogChanged += _tcpHandle_OnConnectLogChanged; ;
    }

    private void _tcpHandle_OnConnectLogChanged(object? sender, ConnectStatusEventArgs e)
    {
        OnConnectStatusChanged?.Invoke(this, e);
    }

    /// <summary>
    /// 获取连接状态
    /// </summary>
    /// <returns></returns>
    public bool GetConnection()
    {
       return _tcpHandle.GetConnection();
    }
    /// <summary>
    /// 获取设备信息
    /// </summary>
    /// <returns></returns>
    public HkOcvFmtEquipDto GetEquipInfo()
    {
        return _group;
    }
    /// <summary>
    /// 获取运行状态
    /// </summary>
    /// <returns></returns>
    public bool GetOperationStatus()
    {
        return _status;
    }

    public async Task<bool> Init(HkOcvFmtEquipDto group, IEnumerable<EquipTagDto> tags = null)
    {
        _group = group;
        _tcpHandle.Init(_connectDataService, _group);

        return true;
    }

    public async Task<bool> OperationStart()
    {
        if (_operationTask != null && GetConnection() && _cancellationTokenSource != null)
        {
           await OperationStop();

        }
        _cancellationTokenSource = new CancellationTokenSource();
        _operationTask = Task.Factory.StartNew(() => ThreadScheduler(), _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        _status = true;
        return true;
    }
    
    private async Task ThreadScheduler()
    {


        while (true)
        {
            try
            {
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    break;
                }


                await _tcpHandle.Execute();

                await PcCommMain();



                await Task.Delay(_group.Pooling);
            }
            catch (Exception exception)
            {
                OnConnectStatusChanged?.Invoke(this, new ConnectStatusEventArgs
                {
                    Message = exception.Message,
                    Connect = false,
                    IsSuccess = false

                });
            }


        }
    }

    /// <summary>
    /// Ims控制
    /// </summary>
    private async Task PcCommMain()
    {


        if (!GetConnection())
        {


           
            _tcpHandle.ConnectServer(_group);
            return;
        }

        if (_tcpHandle.SetDateTimeReq.IsNullOrEmpty())
        {
            await _tcpHandle.COM_SendMessage0002();

            await _tcpHandle.COM_GetStages();

            _group.UpdateStageTime = DateTime.Now;

            return;
        }

        // 间隔一分钟获取最新库位信息
        if (_group.UpdateStageTime!=null &&  DateTime.Now.Subtract(_group.UpdateStageTime.Value).TotalSeconds > new Random().Next(120, 450))
        {

            await _tcpHandle.COM_GetStages();

            _group.UpdateStageTime = DateTime.Now;

            return;
        }
        // 9分钟 心跳
        if (_group.ReadTime!=null && (DateTime.Now - _group.ReadTime.Value).TotalSeconds >= 540.0)
        {
            await _tcpHandle.COM_SendMessage0001();
            _group.ReadTime = DateTime.Now;
            return;
        }


    }

    public async Task<bool> OperationStop()
    {
        _cancellationTokenSource?.Cancel();
        _tcpHandle?.DisconnectServer();
        _status = false;
        return true;
    }

    public async Task<bool> WriteRequest(OperationWriteCommand write)
    {
        if (write.Data.IsNullOrEmpty())
        {
            return false;
        }
       Task.Run(async () =>
        {
            try
            {
                if (_group.EquipType == IotEquipType.FMT.ToString())
                {
                    // 主动发送入库预约
                    if (write.Value  == "0102")
                    {

                        await _tcpHandle.FMT_SendMessage0102(_group, write.Data.ToObject<HkWriteInstruct>());
                    }
                    if (write.Value == "0110")
                    {
                        await _tcpHandle.FMT_SendMessage0102(_group, write.Data.ToObject<HkWriteInstruct>());
                    }
                    // 主动发送入库完成通知
                    if (write.Value == "0103")
                    {
                        await _tcpHandle.FMT_SendMessage0103(_group, write.Data.ToObject<HkWriteInstruct>());
                    }
                    // 主动请求结果
                    if (write.Value == "0105")
                    {
                        await _tcpHandle.FMT_SendMessage0105(_group, write.Data.ToObject<HkWriteInstruct>());
                    }
                    // 出库完成通知
                    if (write.Value == "0107")
                    {
                        await _tcpHandle.FMT_SendMessage0107(_group, write.Data.ToObject<HkWriteInstruct>());
                    }
                    // 模式切换
                    if (write.Value == "0108")
                    {
                        await _tcpHandle.FMT_SendMessage0108(_group, write.Data.ToObject<HkWriteInstruct>());
                    }
                }
                if ((_group.EquipType == IotEquipType.OCV.ToString()) && write.Value == "0208")
                {
                    await _tcpHandle.OCV_SendMessage0208(_group, write.Data.ToObject<HkWriteInstruct>());
                }
                //if (_group.EquipType == HKEquipType.RNK && write.Command == "0608")
                //{
                //    await _tcpHkService.RNK_SendMessage0608(_group, write);
                //}
                //if (_group.EquipType == HKEquipType.CPK && write.Command == "0708")
                //{
                //    await _tcpHkService.CPK_SendMessage0708(_group, write);
                //}
            }
            catch (Exception ex)
            {
                OnConnectStatusChanged?.Invoke(this, new ConnectStatusEventArgs
                {
                    Message = ex.Message,
                    Connect = false,
                    IsSuccess = false

                });
            }

        });
        return true;
    }

    public void Dispose()
    {
        OperationStop();
    }
}
